package com.tledu.ssm.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tledu.ssm.core.entity.AjaxResult;
import com.tledu.ssm.core.exception.LoginException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cyrus
 */
@ControllerAdvice
public class ExceptionContollerAdvice {
    @ExceptionHandler(value = {LoginException.class})
    @ResponseBody
    public AjaxResult<String> handlerException(Exception e, HttpServletRequest request) {
//        if (e instanceof LoginException) {
//            return new AjaxResult<>(403, e.getMessage());
//        } else {
//            return new AjaxResult<>(403, "空指向异常");
//        }
        return new AjaxResult<>(403, e.getMessage());
    }

    @ExceptionHandler(value = {Exception.class})
    public ModelAndView error(Exception e, HttpServletRequest request, HttpServletResponse response) {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            // ajax调用
            e.printStackTrace();
            String sOut = "";
            StackTraceElement[] trace = e.getStackTrace();
            for (StackTraceElement s : trace) {
                sOut += "\tat " + s + "\r\n";
            }

            AjaxResult<String> ajaxResult = new AjaxResult<String>(500,sOut);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(ajaxResult));
            return new ModelAndView(new MappingJackson2JsonView(),jsonObject);
        } else {
            Map<String,Object> map = new HashMap<>();
            map.put("error", e);
            // 网站访问
            return new ModelAndView("error",map);
        }
    }
}
